import ResouceModal from '@/pages/ChatAppPage/components/ResouceModal'
import ThumbsMessage from '@/pages/ChatAppPage/components/ThumbsMessage'
import { useEffect, useRef } from 'react'
import MessageBs from './MessageBs'
import MessageSystem from './MessageSystem'
import MessageUser from './MessageUser'
import RunLog from './RunLog'
import { useChatStore } from './chatStore'

export default function MessagePanne({ useName, loadMore, recommendedHid, conversation = '', chatting = '',uploading = false, regenerate = () => {}, conversationId = '', disabled = false, tips = '', modelName = '', userName = '', supportSearch = false }) {
  const { chatId, messages } = useChatStore()

  // 反馈
  const thumbRef = useRef(null)
  // 溯源
  const sourceRef = useRef(null)

  // 自动滚动
  const messagesRef = useRef(null)
  const scrollLockRef = useRef(false)
  useEffect(() => {
    scrollLockRef.current = false
    queryLockRef.current = false
  }, [chatId])
  useEffect(() => {
    if (scrollLockRef.current) return
    messagesRef.current.scrollTop = messagesRef.current.scrollHeight
  }, [messages])

  // 消息滚动加载
  const queryLockRef = useRef(false)
  useEffect(() => {
    function handleScroll() {
      if (queryLockRef.current) return
      const { scrollTop, clientHeight, scrollHeight } = messagesRef.current
      // 距离底部 600px内，开启自动滚动
      scrollLockRef.current = scrollHeight - scrollTop - clientHeight > 400

      if (messagesRef.current.scrollTop <= 90) {
        console.log('请求 :>> ', 1)
        queryLockRef.current = true
        loadMore()
        // TODO 翻页定位
        // 临时处理防抖
        setTimeout(() => {
          queryLockRef.current = false
        }, 1000)
      }
    }

    messagesRef.current?.addEventListener('scroll', handleScroll)
    return () => messagesRef.current?.removeEventListener('scroll', handleScroll)
  }, [messagesRef.current, messages, chatId])
  
  const paddingBottom = conversation
    ? recommendedHid
      ? uploading ? 'pb-[460px]' : 'pb-[360px]'
      : uploading ? 'pb-[260px]': 'pb-[180px]'
    : recommendedHid
    ? uploading? 'pb-[460px]': 'pb-[360px]'
    : uploading ? 'pb-[260px]': 'pb-[180px]'

  /* 判断知识库 */
  const getCitations = (prevMessages, currentMessage) => {
    return prevMessages?.citations?.length > 0 ? prevMessages.citations : currentMessage?.content?.[0]?.citations ?? []
  }

  const backGrou = conversation ? 'bg-[#ffffff]' : 'bg-[#F5F6F8]'
  return (
    // <div id="message-panne" ref={messagesRef} className="h-full overflow-y-auto pb-60 pt-[56px] scrollbar-hide">
    /* 判断推荐问题 显示paddingbottom距离 */
    <div
      id="message-panne"
      ref={messagesRef}
      className={`h-full overflow-y-auto pt-[56px]  scrollbar-hide ${paddingBottom}`}
    >
      {/* {guideWord && (
        <MessageBs key={9999} data={{ message: guideWord, isSend: false, chatKey: '', end: true, user_name: '' }} />
      )} */}
      {messages.map((msg: any, index) => {
        // 工厂
        let type = 'llm'
        if (msg.role === 'user') {
          type = 'user'
        } else if (msg.role === 'system') {
          type = 'system'
        } else if (msg.role === 'citations') {
          return ''
          // type = 'runLog'
        }
        switch (type) {
          case 'user':
            return <MessageUser key={index} userName={useName} data={msg.content} />
          case 'llm':
            return (
              <MessageBs
                chatting={chatting}
                backGrou={backGrou}
                key={index}
                citations={getCitations(messages[index - 1], msg)}
                data={msg.content[0]}
                nextDataInfo={{
                  // 如果携带citations 上一条没有 找最近的user
                  nextData:
                    messages
                      .slice()
                      .reverse()
                      .find(message => message.role === 'user') || {},
                  index,
                  MaxLength: messages.length,
                  data: msg.content
                }}
                onUnlike={chatId => {
                  thumbRef.current?.openModal(chatId)
                }}
                onSource={data => {
                  sourceRef.current?.openModal(data)
                }}
              />
            )
          case 'system':
            return <MessageSystem key={index} data={msg.content[0]} />
          case 'runLog':
            return <RunLog key={index} data={msg.citations} />
          default:
            return (
              <div className="mt-2 rounded-md border p-2 text-sm" key={index}>
                未知消息类型
              </div>
            )
        }
      })}
      {/* 踩 反馈 */}
      <ThumbsMessage ref={thumbRef}></ThumbsMessage>
      {/* 源文件类型 */}
      <ResouceModal ref={sourceRef}></ResouceModal>
    </div>
  )
}
